package com.thread.sample;

import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestMainSample {

	public static void main(String[] args) {

		System.out.println("System Starting...");
//		ExecutorService executor = Executors.newCachedThreadPool();
		ExecutorService executor = Executors.newFixedThreadPool(3);
		
		CompletionService<Result> comp = new ExecutorCompletionService<>(executor);
		
		for (int i = 0; i < 10; i++) {
			String fileName = "c:\\";
			String keyword = "i'm the world!";
			FileCeatorCallable ceator = new FileCeatorCallable(fileName + i, keyword + i);
			
			comp.submit(ceator);
		}
		
		executor.shutdown();
		
		int index = 0;
		while (index < 10){
			
			Future<Result> res =  comp.poll();
			
			if (res == null)
				continue;
			
			index ++;
			
			try {
				Result result = res.get();
				
				if (result.getCode() == 0){
					System.out.println("Success to create a file.");
					System.out.println("Detail:" + result.getReason());
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}

}
